#!/usr/local/bin/python3
# -*- coding: UTF-8 -*-
import requests
import os,re,IPy,time

def CDNlist(ipC):
    Default=False
    CDN = open('CDN_IPlist.txt').read().split('\n')
    for x in CDN:
        CDN_ip=IPy.IP(x)
        boolIP=(ipC in CDN_ip)
        Default=(Default or boolIP)
    return Default

def dnsR(domian):
    ns=os.popen('nslookup % s ' % domian).read()
    if ns.find('Name:') == -1:
        return []
    else:
        ns=ns[ns.find('Name:'):]
        ip = re.findall('\d+\.\d+\.\d+\.\d+', ns)
        return ip
#https://api.meipai.com/medias/show.json?id=820620550&from=10&language=zh-Hans&client_id=1089857302&device_id=359654060840700&version=6300&channel=qq_cpd&model=SM-G9250&os=6.0.1&origin_channel=qq_cpd&locale=1&iccid=89860086111551164443&imei=359654060840700&mac=02%3A00%3A00%3A00%3A00%3A00&android_id=a5f6071cd589fc61&ab_codes=%5B0%5D&sig=1ba8a73545e8a9800ef9d777d78f9c35&sigVersion=1.3&sigTime=1502862879592

def meipai(meipaiURL):
    try:
        r = requests.get(url=meipaiURL)
        video=r.json()[0]['media']['video']
        domain=r.json()[0]['media']['video'][7:].split("/")[0]
        return domain,video
    except:
        return "打开错误！","打开错误！"


def main(URL):
    meipai_Domain,video = meipai(URL)
    meipai_IP = dnsR(meipai_Domain)
    if len(meipai_IP) == 0:
        flag = "无解析结果"
    else:
        if CDNlist(meipai_IP[0]):
            # print(miaopai_ip)
            flag = '网内'
        else:
            flag = '出网'
        return (video,flag, "<br>".join(meipai_IP))
if __name__ == '__main__':
    URL='https://api.meipai.com/hot/feed_timeline.json?page=1&guid=990cb3dfb9d00c2ba105a3ceeddd5e6a&language=zh-Hans&client_id=1089857302&device_id=359654060840700&version=6300&channel=qq_cpd&model=SM-G9250&os=6.0.1&origin_channel=qq_cpd&locale=1&iccid=89860086111551164443&imei=359654060840700&mac=02%3A00%3A00%3A00%3A00%3A00&android_id=a5f6071cd589fc61&ab_codes=%5B0%5D&sig=03cc322b814336060dfa83da638df1e3&sigVersion=1.3&sigTime=1503036522800'

    for i in range(10):
        t=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        res = main(URL)
        print('%s\t%s\t%s\n' % res)
        fLog=open('/var/www/html/short_video/%sShortVideoLog.txt'% time.strftime("%Y-%m-%d", time.localtime()),'a' )
        fLog.write(t+'\t美拍\t%s\t%s\t%s\n' % res)
        fLog.close()